package com.allm.ai.api.controller;

import com.allm.ai.common.entity.AiModel;
import com.allm.ai.common.service.AiModelService;
import com.allm.ai.common.service.ChatModelCacheService;
import com.allm.ai.common.strategy.impl.DeepSeekStrategy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 缓存管理控制器
 * 提供 ChatModel 和 ChatClient 缓存的监控和管理功能
 */
@Slf4j
@RestController
@RequestMapping("/cache")
@CrossOrigin(origins = "*", allowedHeaders = "*")
@RequiredArgsConstructor
public class CacheManagementController {
    
    private final ChatModelCacheService cacheService;
    private final DeepSeekStrategy deepSeekStrategy;
    private final AiModelService aiModelService;
    
    /**
     * 获取缓存统计信息
     */
    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getCacheStats() {
        try {
            Map<String, Object> stats = cacheService.getCacheStats();
            stats.put("timestamp", LocalDateTime.now());
            stats.put("status", "success");
            
            return ResponseEntity.ok(stats);
        } catch (Exception e) {
            log.error("获取缓存统计失败", e);
            return ResponseEntity.internalServerError()
                .body(Map.of(
                    "status", "error",
                    "message", e.getMessage(),
                    "timestamp", LocalDateTime.now()
                ));
        }
    }
    
    /**
     * 获取缓存健康状态
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> getCacheHealth() {
        try {
            Map<String, Object> health = cacheService.getHealthStatus();
            return ResponseEntity.ok(health);
        } catch (Exception e) {
            log.error("获取缓存健康状态失败", e);
            return ResponseEntity.internalServerError()
                .body(Map.of(
                    "status", "ERROR",
                    "message", e.getMessage(),
                    "timestamp", LocalDateTime.now()
                ));
        }
    }
    
    /**
     * 清理所有缓存
     */
    @DeleteMapping("/clear-all")
    public ResponseEntity<Map<String, Object>> clearAllCache() {
        try {
            Map<String, Object> beforeStats = cacheService.getCacheStats();
            
            cacheService.clearAllCache();
            
            Map<String, Object> result = new HashMap<>();
            result.put("status", "success");
            result.put("message", "所有缓存已清理");
            result.put("beforeStats", beforeStats);
            result.put("timestamp", LocalDateTime.now());
            
            log.info("手动清理所有缓存");
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("清理所有缓存失败", e);
            return ResponseEntity.internalServerError()
                .body(Map.of(
                    "status", "error",
                    "message", e.getMessage(),
                    "timestamp", LocalDateTime.now()
                ));
        }
    }
    
    /**
     * 清理特定模型的缓存
     */
    @DeleteMapping("/clear/{modelId}")
    public ResponseEntity<Map<String, Object>> clearModelCache(@PathVariable Long modelId) {
        try {
            Optional<AiModel> modelOpt = aiModelService.findById(modelId);
            if (modelOpt.isEmpty()) {
                return ResponseEntity.badRequest()
                    .body(Map.of(
                        "status", "error",
                        "message", "模型不存在: " + modelId,
                        "timestamp", LocalDateTime.now()
                    ));
            }
            
            AiModel model = modelOpt.get();
            cacheService.clearCache(model);
            
            Map<String, Object> result = new HashMap<>();
            result.put("status", "success");
            result.put("message", "模型缓存已清理");
            result.put("modelId", modelId);
            result.put("modelName", model.getName());
            result.put("timestamp", LocalDateTime.now());
            
            log.info("手动清理模型缓存: {}", model.getName());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("清理模型缓存失败", e);
            return ResponseEntity.internalServerError()
                .body(Map.of(
                    "status", "error",
                    "message", e.getMessage(),
                    "modelId", modelId,
                    "timestamp", LocalDateTime.now()
                ));
        }
    }
    
    /**
     * 预热缓存 - 为指定模型创建缓存
     */
    @PostMapping("/warmup/{modelId}")
    public ResponseEntity<Map<String, Object>> warmupCache(@PathVariable Long modelId) {
        try {
            Optional<AiModel> modelOpt = aiModelService.findById(modelId);
            if (modelOpt.isEmpty()) {
                return ResponseEntity.badRequest()
                    .body(Map.of(
                        "status", "error",
                        "message", "模型不存在: " + modelId,
                        "timestamp", LocalDateTime.now()
                    ));
            }
            
            AiModel model = modelOpt.get();
            
            // 预热缓存：创建 ChatModel 和 ChatClient
            cacheService.getOrCreateChatModel(model);
            cacheService.getOrCreateChatClient(model);
            cacheService.getOrCreateSimpleChatClient(model);
            
            Map<String, Object> result = new HashMap<>();
            result.put("status", "success");
            result.put("message", "缓存预热完成");
            result.put("modelId", modelId);
            result.put("modelName", model.getName());
            result.put("timestamp", LocalDateTime.now());
            
            log.info("缓存预热完成: {}", model.getName());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("缓存预热失败", e);
            return ResponseEntity.internalServerError()
                .body(Map.of(
                    "status", "error",
                    "message", e.getMessage(),
                    "modelId", modelId,
                    "timestamp", LocalDateTime.now()
                ));
        }
    }
    
    /**
     * 测试模型连接
     */
    @PostMapping("/test/{modelId}")
    public ResponseEntity<Map<String, Object>> testModelConnection(@PathVariable Long modelId) {
        try {
            Optional<AiModel> modelOpt = aiModelService.findById(modelId);
            if (modelOpt.isEmpty()) {
                return ResponseEntity.badRequest()
                    .body(Map.of(
                        "status", "error",
                        "message", "模型不存在: " + modelId,
                        "timestamp", LocalDateTime.now()
                    ));
            }
            
            AiModel model = modelOpt.get();
            
            // 只对 DeepSeek 模型进行测试
            if (!deepSeekStrategy.supports(model.getServiceProvider())) {
                return ResponseEntity.badRequest()
                    .body(Map.of(
                        "status", "error",
                        "message", "不支持的服务提供商: " + model.getServiceProvider(),
                        "modelId", modelId,
                        "timestamp", LocalDateTime.now()
                    ));
            }
            
            long startTime = System.currentTimeMillis();
            String response = deepSeekStrategy.testConnection(model);
            long endTime = System.currentTimeMillis();
            
            Map<String, Object> result = new HashMap<>();
            result.put("status", "success");
            result.put("message", "连接测试成功");
            result.put("modelId", modelId);
            result.put("modelName", model.getName());
            result.put("response", response);
            result.put("responseTime", endTime - startTime + "ms");
            result.put("timestamp", LocalDateTime.now());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("模型连接测试失败", e);
            return ResponseEntity.internalServerError()
                .body(Map.of(
                    "status", "error",
                    "message", e.getMessage(),
                    "modelId", modelId,
                    "timestamp", LocalDateTime.now()
                ));
        }
    }
    
    /**
     * 获取详细的缓存信息页面
     */
    @GetMapping("/dashboard")
    public ResponseEntity<String> getCacheDashboard() {
        try {
            Map<String, Object> stats = cacheService.getCacheStats();
            Map<String, Object> health = cacheService.getHealthStatus();
            
            String html = String.format("""
                <!DOCTYPE html>
                <html>
                <head>
                    <title>缓存管理仪表板</title>
                    <meta charset="UTF-8">
                    <style>
                        body { font-family: Arial, sans-serif; margin: 20px; }
                        .container { max-width: 1200px; margin: 0 auto; }
                        .card { border: 1px solid #ddd; border-radius: 8px; padding: 20px; margin-bottom: 20px; }
                        .stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; }
                        .stat-item { background: #f5f5f5; padding: 15px; border-radius: 5px; text-align: center; }
                        .stat-value { font-size: 24px; font-weight: bold; color: #007bff; }
                        .stat-label { color: #666; margin-top: 5px; }
                        .health-status { padding: 10px; border-radius: 5px; text-align: center; font-weight: bold; }
                        .healthy { background-color: #d4edda; color: #155724; }
                        .warning { background-color: #fff3cd; color: #856404; }
                        .actions { display: flex; gap: 10px; flex-wrap: wrap; }
                        .btn { padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; text-decoration: none; }
                        .btn-primary { background-color: #007bff; color: white; }
                        .btn-warning { background-color: #ffc107; color: black; }
                        .btn-danger { background-color: #dc3545; color: white; }
                        .btn:hover { opacity: 0.8; }
                        pre { background: #f8f9fa; padding: 15px; border-radius: 5px; overflow-x: auto; }
                        .refresh-info { color: #666; font-size: 12px; margin-top: 10px; }
                    </style>
                </head>
                <body>
                    <div class="container">
                        <h1>ChatModel 缓存管理仪表板</h1>
                        
                        <div class="card">
                            <h2>健康状态</h2>
                            <div class="health-status %s">
                                状态: %s
                            </div>
                            <div class="stats">
                                <div class="stat-item">
                                    <div class="stat-value">%s</div>
                                    <div class="stat-label">ChatModel 使用率</div>
                                </div>
                                <div class="stat-item">
                                    <div class="stat-value">%s</div>
                                    <div class="stat-label">ChatClient 使用率</div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="card">
                            <h2>缓存统计</h2>
                            <div class="stats">
                                <div class="stat-item">
                                    <div class="stat-value">%d</div>
                                    <div class="stat-label">ChatModel 缓存数量</div>
                                </div>
                                <div class="stat-item">
                                    <div class="stat-value">%d</div>
                                    <div class="stat-label">ChatClient 缓存数量</div>
                                </div>
                                <div class="stat-item">
                                    <div class="stat-value">%d</div>
                                    <div class="stat-label">最大缓存数量</div>
                                </div>
                                <div class="stat-item">
                                    <div class="stat-value">%d</div>
                                    <div class="stat-label">缓存TTL(小时)</div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="card">
                            <h2>管理操作</h2>
                            <div class="actions">
                                <button class="btn btn-primary" onclick="refreshPage()">刷新页面</button>
                                <button class="btn btn-warning" onclick="clearAllCache()">清理所有缓存</button>
                                <button class="btn btn-primary" onclick="showStats()">查看详细统计</button>
                            </div>
                        </div>
                        
                        <div class="card">
                            <h2>详细信息</h2>
                            <pre id="detailInfo">点击"查看详细统计"按钮查看详细信息</pre>
                        </div>
                        
                        <div class="refresh-info">
                            页面生成时间: %s<br>
                            注意: 此页面显示的是静态数据，点击刷新按钮获取最新信息
                        </div>
                    </div>
                    
                    <script>
                        function refreshPage() {
                            location.reload();
                        }
                        
                        function clearAllCache() {
                            if (confirm('确定要清理所有缓存吗？')) {
                                fetch('/api/cache/clear-all', { method: 'DELETE' })
                                    .then(response => response.json())
                                    .then(data => {
                                        alert(data.message || '操作完成');
                                        refreshPage();
                                    })
                                    .catch(error => {
                                        alert('操作失败: ' + error.message);
                                    });
                            }
                        }
                        
                        function showStats() {
                            fetch('/api/cache/stats')
                                .then(response => response.json())
                                .then(data => {
                                    document.getElementById('detailInfo').textContent = JSON.stringify(data, null, 2);
                                })
                                .catch(error => {
                                    document.getElementById('detailInfo').textContent = '获取统计信息失败: ' + error.message;
                                });
                        }
                    </script>
                </body>
                </html>
                """,
                health.get("status").equals("HEALTHY") ? "healthy" : "warning",
                health.get("status"),
                health.get("chatModelUsage"),
                health.get("chatClientUsage"),
                stats.get("chatModelCacheSize"),
                stats.get("chatClientCacheSize"),
                stats.get("maxCacheSize"),
                stats.get("cacheTtlHours"),
                LocalDateTime.now()
            );
            
            return ResponseEntity.ok()
                .header("Content-Type", "text/html; charset=utf-8")
                .body(html);
        } catch (Exception e) {
            log.error("生成缓存仪表板失败", e);
            return ResponseEntity.internalServerError()
                .body("<html><body><h1>错误</h1><p>" + e.getMessage() + "</p></body></html>");
        }
    }
} 